"""
日志配置模块
集中管理所有日志相关的配置
"""
import os
from typing import Dict, Any


class LoggingConfig:
    """日志配置类"""
    
    # 日志级别映射
    LOG_LEVELS = {
        'DEBUG': 10,
        'INFO': 20,
        'WARNING': 30,
        'ERROR': 40,
        'CRITICAL': 50
    }
    
    # 默认配置
    DEFAULT_CONFIG = {
        'level': 'INFO',
        'max_bytes': 10 * 1024 * 1024,  # 10MB
        'backup_count': 5,
        'encoding': 'utf-8',
        'log_dir': 'logs'
    }
    
    @staticmethod
    def get_log_config() -> Dict[str, Any]:
        """获取日志配置"""
        config = LoggingConfig.DEFAULT_CONFIG.copy()
        
        # 从环境变量覆盖配置
        config['level'] = os.environ.get('LOG_LEVEL', config['level']).upper()
        config['max_bytes'] = int(os.environ.get('LOG_MAX_BYTES', config['max_bytes']))
        config['backup_count'] = int(os.environ.get('LOG_BACKUP_COUNT', config['backup_count']))
        config['log_dir'] = os.environ.get('LOG_DIR', config['log_dir'])
        
        return config
    
    @staticmethod
    def get_log_format_configs() -> Dict[str, str]:
        """获取日志格式配置"""
        return {
            'detailed': (
                "%(asctime)s [%(levelname)s] %(name)s - %(message)s "
                "(%(filename)s:%(lineno)d) [%(funcName)s] [PID:%(process)d]"
            ),
            'api': (
                "%(asctime)s [API] [%(levelname)s] %(message)s [PID:%(process)d]"
            ),
            'business': (
                "%(asctime)s [BUSINESS] %(name)s - %(message)s "
                "(%(filename)s:%(lineno)d) [PID:%(process)d]"
            ),
            'error': (
                "%(asctime)s [ERROR] %(name)s - %(message)s "
                "(%(filename)s:%(lineno)d) [%(funcName)s] [PID:%(process)d]"
            ),
            'simple': (
                "%(asctime)s [%(levelname)s] %(message)s"
            )
        }
    
    @staticmethod
    def get_logger_configs() -> Dict[str, Dict[str, Any]]:
        """获取各类日志器配置"""
        base_config = LoggingConfig.get_log_config()
        
        return {
            'app': {
                'filename': 'backend.log',
                'format': 'detailed',
                'level': base_config['level'],
                'max_bytes': base_config['max_bytes'],
                'backup_count': base_config['backup_count'],
                'handler_type': 'rotating'
            },
            'api': {
                'filename': 'api_access.log',
                'format': 'api',
                'level': 'INFO',
                'max_bytes': base_config['max_bytes'],
                'backup_count': 30,
                'handler_type': 'timed_rotating',
                'when': 'midnight',
                'interval': 1
            },
            'error': {
                'filename': 'error.log',
                'format': 'error',
                'level': 'ERROR',
                'max_bytes': base_config['max_bytes'],
                'backup_count': 10,
                'handler_type': 'rotating'
            },
            'database': {
                'filename': 'database.log',
                'format': 'detailed',
                'level': 'DEBUG' if base_config['level'] == 'DEBUG' else 'INFO',
                'max_bytes': base_config['max_bytes'],
                'backup_count': 7,
                'handler_type': 'timed_rotating',
                'when': 'midnight',
                'interval': 1
            },
            'flink_api': {
                'filename': 'flink_api.log',
                'format': 'detailed',
                'level': 'INFO',
                'max_bytes': base_config['max_bytes'],
                'backup_count': 7,
                'handler_type': 'timed_rotating',
                'when': 'midnight',
                'interval': 1
            }
        }
    
    @staticmethod
    def get_log_file_patterns() -> Dict[str, str]:
        """获取日志文件命名模式"""
        return {
            'rotating': '{filename}',
            'timed_rotating': '{filename}',
            'daily': '{basename}_{date}.log',
            'hourly': '{basename}_{datetime}.log'
        }
    
    @staticmethod
    def get_cleanup_config() -> Dict[str, Any]:
        """获取日志清理配置"""
        return {
            'enabled': os.environ.get('LOG_CLEANUP_ENABLED', 'true').lower() == 'true',
            'max_age_days': int(os.environ.get('LOG_MAX_AGE_DAYS', '30')),
            'cleanup_hour': int(os.environ.get('LOG_CLEANUP_HOUR', '2')),
            'cleanup_minute': int(os.environ.get('LOG_CLEANUP_MINUTE', '0')),
            'min_free_space_gb': float(os.environ.get('LOG_MIN_FREE_SPACE_GB', '1.0'))
        }
    
    @staticmethod
    def validate_config(config: Dict[str, Any]) -> bool:
        """验证配置有效性"""
        try:
            # 验证日志级别
            if config.get('level') not in LoggingConfig.LOG_LEVELS:
                return False
            
            # 验证数值配置
            if config.get('max_bytes', 0) <= 0:
                return False
                
            if config.get('backup_count', 0) < 0:
                return False
            
            return True
            
        except Exception:
            return False


# 日志配置常量
LOGGING_CONFIG = LoggingConfig.get_log_config()
LOGGER_CONFIGS = LoggingConfig.get_logger_configs()
LOG_FORMATS = LoggingConfig.get_log_format_configs()
CLEANUP_CONFIG = LoggingConfig.get_cleanup_config()


# 导出配置
__all__ = [
    'LoggingConfig',
    'LOGGING_CONFIG', 
    'LOGGER_CONFIGS',
    'LOG_FORMATS',
    'CLEANUP_CONFIG'
]
